package com.dd.ent.car.ui.user;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.support.annotation.NonNull;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnFocusChangeListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.dd.ent.car.R;
import com.dd.ent.car.common.bean.User;
import com.dd.ent.car.common.config.UIConfig;
import com.dd.ent.car.common.player.XLAlarmDialog;
import com.dd.ent.car.service.user.UserService;
import com.dd.ent.car.ui.BaseActivity;
import com.duanqu.qupai.utils.ToastUtils;
import com.pp.ent.base.log.MLog;
import com.pp.ent.core.manage.UIHandler;
import com.pp.ent.view.annotation.ContentView;
import com.pp.ent.view.annotation.Inject;
import com.pp.ent.view.annotation.ViewInject;

import cn.smssdk.EventHandler;
import cn.smssdk.SMSSDK;

import static android.widget.Toast.LENGTH_LONG;


/**
 * Created by Sun Yuan on 2016/5/30.
 *
 * @author Sun Yuan
 */
@ContentView(R.layout.activity_find_password_layout)
public class FindPasswordActivity extends BaseActivity {
    private static final String TAG = FindPasswordActivity.class.getSimpleName();
    public static final String TYPE = "type";
    public static final String PHONE_NUMBER = "phone_number";
    public static final int TYPE_LOGIN = 1; // 登陆
    public static final int TYPE_REGISTER = 2; // 注册

    @ViewInject(R.id.titlebar_title)
    private TextView tvTitle;
    @ViewInject(R.id.et_phone_num)
    private EditText mEtPhoneNum;
    @ViewInject(R.id.tv_send_verify_code)
    private TextView mTvSendVerifyCode;
    @ViewInject(R.id.tv_time_count_down)
    private TextView mtvTimeCountDown; //计时器，验证码60秒过期
    @ViewInject(R.id.et_verify_code)
    private EditText mEtVerifyCode;
    @ViewInject(R.id.iv_icon_mobile)
    private ImageView mIvPhone;
    @ViewInject(R.id.iv_icon_verify_code)
    private ImageView mIvVerifyCode;
    @ViewInject(R.id.iv_icon_password)
    private ImageView mIvPassword;
    @ViewInject(R.id.btn_submit)
    private View mBtnSubmit;
    @ViewInject(R.id.iv_clear_verify_code)
    private View mIvClear;

    @Inject
    private UserService userService;

    private ProgressDialog mProgressDialog;
    private String mPhoneNumber;
    private CountDownHelper mCountDownHelper;

    public static void startSlef(Context context) {
        Intent intent = new Intent(context, FindPasswordActivity.class);
        context.startActivity(intent);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Intent intent = getIntent();
        mPhoneNumber = intent.getStringExtra(PHONE_NUMBER);
        init();
    }

    private void init() {
        tvTitle.setText("找回密码");
        SMSSDK.registerEventHandler(new EventHandler() {
            @Override
            public void afterEvent(int event, int result, Object data) {
                if (result == SMSSDK.RESULT_COMPLETE) {
                    MLog.debug(TAG, "event =" + event);
                    //回调完成
                    if (event == SMSSDK.EVENT_SUBMIT_VERIFICATION_CODE) {
                        //提交验证码成功
                        findThePassword();
                    } else if (event == SMSSDK.EVENT_GET_VERIFICATION_CODE) {
                        //获取验证码成功
                    } else if (event == SMSSDK.EVENT_GET_SUPPORTED_COUNTRIES) {
                        //返回支持发送验证码的国家列表
                    }
                } else {
                }
            }
        });
        addListener();
    }

    private void addListener() {
        mTvSendVerifyCode.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (isCorrectNumber()) {
                    sendVerifyCodeOnClick();
                }
            }
        });
        mBtnSubmit.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                submitBtnOnClick(v);
            }
        });
        mIvClear.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                mEtVerifyCode.setText("");
            }
        });
        mEtPhoneNum.addTextChangedListener(new TextWatcher() {
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                changeButtonEnableState();
            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void afterTextChanged(Editable s) {
            }
        });
        mEtPhoneNum.setOnFocusChangeListener(new OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                mIvPhone.setImageDrawable(getResources().getDrawable(hasFocus ? R.drawable.icon_mobile_focused : R.drawable.icon_mobile));
            }
        });
        mEtVerifyCode.setOnFocusChangeListener(new OnFocusChangeListener() {

            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (hasFocus) {
                    mIvClear.setVisibility(mEtVerifyCode.length() > 0 ? View.VISIBLE : View.GONE);
                    mIvVerifyCode.setImageDrawable(getResources().getDrawable(R.drawable.icon_verify_code_focused));
                } else {
                    mIvClear.setVisibility(View.GONE);
                    mIvVerifyCode.setImageDrawable(getResources().getDrawable(R.drawable.icon_verify_code));
                }
            }
        });
        mEtVerifyCode.addTextChangedListener(new TextWatcher() {

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (s != null && s.length() > 0) {
                    mIvClear.setVisibility(View.VISIBLE);
                } else {
                    mIvClear.setVisibility(View.INVISIBLE);
                }
                changeButtonEnableState();
            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });

    }

    protected void sendVerifyCodeOnClick() {
        startCountDown();
        mPhoneNumber = mEtPhoneNum.getText().toString();
        mEtVerifyCode.setText("");
        doSendMsg();
    }

    private void submitBtnOnClick(View v) {
        hiddenInput(v);
        if (isCorrectNumber() && isCorrectValid()) {
            submitOnClick();
        } else {
            dismissProgressDialog();
        }
    }

    protected void submitOnClick() {
        sumbitVerificationCode();
    }

    private void findThePassword() {
        String phoneNumber = getPhoneNumber();
        userService.findPassword(phoneNumber);

    }

    @NonNull
    protected String getPhoneNumber() {
        return mEtPhoneNum.getText().toString();
    }

    @NonNull
    protected String getMsgVerifyCode() {
        return mEtVerifyCode.getText().toString();
    }

    @Override
    protected void onResume() {
        super.onResume();
        changeButtonEnableState();
    }

    @Override
    protected void onStop() {
        super.onStop();
        dismissProgressDialog();
    }

    protected void onDestroy() {
        super.onDestroy();
        if (mCountDownHelper != null) {
            mCountDownHelper.stop();
        }
    }


    private void registerSuccess() {
    }

    protected void login(final boolean isNewRegister) {
    }


    protected void showTip(int resId) {
        showTip(getString(resId));
    }

    protected void showTip(String msg) {
    }

    protected void showErrorTip(String msg) {
        dismissProgressDialog();
        Toast.makeText(this, msg, LENGTH_LONG).show();
    }

    protected void showErrorTip(int resId) {
        showErrorTip(getString(resId));
    }

    protected void showProgressDialog(int message) {
        dismissProgressDialog();
        mProgressDialog = new ProgressDialog(this);
        mProgressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        mProgressDialog.setMessage(getResources().getString(message));
        mProgressDialog.setCancelable(false);
        mProgressDialog.show();
    }

    protected void dismissProgressDialog() {
        if (null != mProgressDialog) {
            mProgressDialog.dismiss();
            mProgressDialog = null;
        }
    }

    private boolean isCorrectNumber() {
        String number = getPhoneNumber();
        if (TextUtils.isEmpty(number)) {// 手机号没输入
            showErrorTip(getString(R.string.register_please_input_phone_number));
            return false;
        } else if (!number.matches("^1[0-9]{10}$")) {// 手机号不符合
            showErrorTip(getString(R.string.register_please_input_correct_phone_number));
            return false;
        } else {
            return true;
        }
    }

    private boolean isCorrectValid() {
        String number = getMsgVerifyCode();
        if (TextUtils.isEmpty(number)) {// 验证码没输入
            showErrorTip(getString(R.string.register_please_input_sms_verify_code));
            return false;
        }
        return true;
    }

    /**
     * 发送验证码
     */
    private void doSendMsg() {
        SMSSDK.getVerificationCode("86", mPhoneNumber);
    }

    /**
     * 提交验证码验证
     */
    private void sumbitVerificationCode() {
        hiddenInput(mBtnSubmit);
        if (isCorrectNumber() && isCorrectValid()) {
            showProgressDialog(R.string.loading);
            String number = getMsgVerifyCode();
            SMSSDK.submitVerificationCode("+86", mPhoneNumber, number);
        }
    }

    protected void startCountDown() {
        mCountDownHelper = new CountDownHelper(new CountDownHelper.OnCountDownListener() {
            @Override
            public void onCountDown(int count) {
                showValidText(count);
            }
        });
        mCountDownHelper.start();
    }

    private void showSoftKeyboard(View view) {
        if (view.requestFocus()) {
            InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
            imm.showSoftInput(view, InputMethodManager.SHOW_IMPLICIT);
        }
    }

    private void hiddenInput(View v) {
        InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        inputMethodManager.hideSoftInputFromWindow(v.getWindowToken(), 0);
    }

    private void showValidText(int count) {
        if (count > 0) {
            mtvTimeCountDown.setText(String.format("%s秒后重新获取", count));
            mtvTimeCountDown.setVisibility(View.VISIBLE);
            mTvSendVerifyCode.setVisibility(View.GONE);
        } else {
            mtvTimeCountDown.setVisibility(View.GONE);
            mTvSendVerifyCode.setVisibility(View.VISIBLE);
        }
    }

    /**
     * 设置按钮是否可以点击的状态
     */
    private void changeButtonEnableState() {
        if (mEtPhoneNum.getText().length() > 0) {
            if (mEtVerifyCode.getText().length() > 0) {
                mBtnSubmit.setEnabled(true);
            } else {
                mBtnSubmit.setEnabled(false);
            }
            mTvSendVerifyCode.setEnabled(true);
        } else {
            mBtnSubmit.setEnabled(false);
            mTvSendVerifyCode.setEnabled(false);
        }
    }

    @UIHandler(UIConfig.FIND_PASSWORD_FAIL)
    public void findPaswwordFailResopnse() {
        ToastUtils.showToast(this, "手机号码不存在，请重新注册");
        dismissProgressDialog();
    }


    @UIHandler(UIConfig.FIND_PASSWORD_SUCCESS)
    public void findPaswwordSuccessResopnse(User user) {
        dismissProgressDialog();
        final XLAlarmDialog xlAlarmDialog = new XLAlarmDialog(this);
        xlAlarmDialog.setTitle("找回密码成功");
        xlAlarmDialog.setContent("密码是：" + user.getPassword());
        xlAlarmDialog.setRightBtnStr("登录");
        xlAlarmDialog.setOnClickConfirmButtonListener(new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                xlAlarmDialog.dismiss();
                finish();
            }
        });
        xlAlarmDialog.show();
    }


    private static class CountDownHelper {

        public interface OnCountDownListener {
            void onCountDown(int count);
        }

        private static final int MAX_COUNT = 60;
        private volatile boolean isStop = false;
        private Handler mHandler;
        private Thread mCountDownThread;

        public CountDownHelper(final OnCountDownListener onCountDownListener) {
            mHandler = new Handler(Looper.getMainLooper()) {
                @Override
                public void handleMessage(Message msg) {
                    if (onCountDownListener != null) {
                        onCountDownListener.onCountDown(msg.what);
                    }
                }
            };
            mCountDownThread = new Thread(new Runnable() {
                @Override
                public void run() {
                    int count = MAX_COUNT;
                    while (count-- > 0) {
                        if (!isStop) {
                            mHandler.sendEmptyMessage(count);
                            try {
                                Thread.sleep(1000);
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                        }
                    }
                }
            });
        }

        public void start() {
            mCountDownThread.start();
        }

        public void stop() {
            isStop = true;
        }
    }
}
